from celery.result import AsyncResult
from flask import Blueprint, jsonify, request, render_template

from applications.common.curd import model_to_dicts
from applications.common.tasks.spider_tasks import crawl_cwzx_task
from applications.common.utils.http import table_api
from applications.common.utils.validate import str_escape
from applications.models import FundStockListCwzx
from applications.schemas import FundStockCWZXSchema
from sqlalchemy import func, desc

fund_bp = Blueprint('fund', __name__, url_prefix='/fund')


@fund_bp.get('/startCwzxTask')
def start_cwzx_task():
    task = crawl_cwzx_task.delay()
    task_result = AsyncResult(task.id)
    result = {
        "task_id": task.id,
        "task_status": task_result.status,
        "task_result": task_result.result
    }
    return jsonify(result)


@fund_bp.get('/')
def main():
    create_dates_query = FundStockListCwzx.query.with_entities(FundStockListCwzx.create_date).distinct() \
        .order_by(desc('create_date')).all()
    industrys_query = FundStockListCwzx.query.with_entities(FundStockListCwzx.industry,
                                                            func.round(func.sum(FundStockListCwzx.percent), 2).label(
                                                                'total_percent')) \
        .group_by(FundStockListCwzx.industry).order_by(desc('total_percent')).all()
    manipulate_query = FundStockListCwzx.query.with_entities(FundStockListCwzx.manipulate).distinct().all()
    control_level_query = FundStockListCwzx.query.with_entities(FundStockListCwzx.control_level).distinct().all()
    average_posi_query = FundStockListCwzx.query.with_entities(FundStockListCwzx.average_posi).distinct().all()
    create_dates = [create_date[0] for create_date in create_dates_query]
    industrys = [(industry[0], str(industry[1])) for industry in industrys_query]
    manipulates = [manipulate[0] for manipulate in manipulate_query]
    control_levels = [control_level[0] for control_level in control_level_query]
    average_posis = [average_posi[0] for average_posi in average_posi_query]
    return render_template('fund/cwzx/main.html', create_dates=create_dates, industrys=industrys,
                           manipulates=manipulates, control_levels=control_levels, average_posis=average_posis)


@fund_bp.get('/data')
def table():
    create_date = str_escape(request.args.get('createDate', type=str))
    industry = str_escape(request.args.get('industry', type=str))
    manipulate = str_escape(request.args.get('manipulate', type=str))
    control_level = str_escape(request.args.get('controlLevel', type=str))
    average_posi = str_escape(request.args.get('averagePosi', type=str))
    start_per_ttm = str_escape(request.args.get('startPerTtm', type=str))
    end_per_ttm = str_escape(request.args.get('endPerTtm', type=str))
    stock_code = str_escape(request.args.get('stockCode', type=str))
    filters = []
    if create_date:
        filters.append(FundStockListCwzx.create_date == create_date)
    if industry:
        filters.append(FundStockListCwzx.industry == industry)
    if manipulate:
        filters.append(FundStockListCwzx.manipulate == manipulate)
    if control_level:
        filters.append(FundStockListCwzx.control_level == control_level)
    if average_posi:
        filters.append(FundStockListCwzx.average_posi == average_posi)
    if start_per_ttm:
        filters.append(FundStockListCwzx.per_ttm >= start_per_ttm)
    if end_per_ttm:
        filters.append(FundStockListCwzx.per_ttm <= end_per_ttm)
    if stock_code:
        filters.append(FundStockListCwzx.stock_code == stock_code)

    stock_list = FundStockListCwzx.query.filter(*filters).layui_paginate()
    return table_api(data=model_to_dicts(schema=FundStockCWZXSchema, data=stock_list.items), count=stock_list.total)








